package com.atguigu.lease.web.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author 51560
 * @project lease
 * @title 批量制造转化器
 * @package com.atguigu.lease.web.converter
 * @since 2025/5/9 9:55
 */
@Component
public class String2BaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                // 获取枚举的全部值
                T[] values = (T[]) targetType.getEnumConstants();
                // 循环获取枚举的getCode和getName
                // 如果source相同直接返回类型
                for (T value : values) {
                    if (source.equals(value.getCode().toString())) {
                        return value;
                    }
                }
                // 循环以后没有，抛出异常
                throw new RuntimeException("非法类型异常!");
            }
        };
    }
}
